import * as React from'react'
import { vscode } from '../utils/vscode'
import { MessageType } from '../../../src/utils/MessageHandler'
import { useEvent } from 'react-use'
import { DatabaseParam, ProjectTemplateParam, ModelInfoParam, HighlightjsParam } from '../../../src/store/types'

export default React.memo(function() {
	const modelInfoFormRef = React.useRef<HTMLFormElement>(null)
	const databaseFormRef = React.useRef<HTMLFormElement>(null)
	const projectTemplateFormRef = React.useRef<HTMLFormElement>(null)
	const highlightjsFormRef = React.useRef<HTMLFormElement>(null)
	const [config, setConfig ] = React.useState<{
		database?: DatabaseParam
		projectTemplate?: ProjectTemplateParam
		modelInfo?: ModelInfoParam
		highlightjs?: HighlightjsParam
	}>({
		modelInfo: {
			modelName: 'deepseek/deepseek-chat',
			apiKey: '',
		},
		highlightjs: {
			theme: 'dark',
			themes: ['dark', 'light'],
			content: ''
		}
	})


	const handleMessage = React.useCallback((e: MessageEvent) => {
		const message = e.data 
		console.log('设置页面收到消息', message)
		if(message.type === MessageType.getConfig) {
			setConfig({
				...config,
				...message.data
			})
		}
		if(message.type === MessageType.getThemeContent) {
			const element: any = document.querySelector('.highlightjs-form vscode-textarea[name="content"]')
			element.value = message.data
		}
	}, [config])

	const handleSave = React.useCallback((formRef:  React.RefObject<HTMLFormElement | null>, e:  React.FormEvent<HTMLFormElement>, key: string) => {
		e.preventDefault();
		e.stopPropagation();
		if(!formRef.current?.checkValidity()) {
			return
		}
		const formData = new FormData(formRef.current)
		let newConfig = {
			...config
		}
		const firstKey = key
		for(const [secondKey, value] of formData.entries()) {
			newConfig = {
				...newConfig,
				[firstKey]: {
					...newConfig[firstKey as keyof typeof config],
					[secondKey]: value
				}
			}
			setConfig(newConfig)
		}
		vscode.postMessage({
			type: MessageType.setConfig,
			data: {
				[key]: newConfig[key	as keyof typeof config]
			}
		})
	}, [config])

	const handleReset = React.useCallback((e:  React.FormEvent<HTMLFormElement>, key: string) => {
		e.preventDefault();
		e.stopPropagation();
		vscode.postMessage({
			type: MessageType.getConfig,
			data: {
				key
			}
		})
	}, [])

	const handleThemeChange = React.useCallback((evt: any) => {
		const themeName = evt.target.value
		vscode.postMessage({
			type: MessageType.getThemeContent,	
			data: {
				themeName: themeName
			}
		})
	}, [])

	useEvent('message', handleMessage)

	React.useEffect(() => {
		console.log('设置页面')	

		vscode.postMessage({
			type: MessageType.getConfig
		})

		return () => {
			console.log('设置页面卸载')	
		}
	}, [])

	React.useEffect(() => {
		document.querySelector('.highlightjs-form vscode-single-select[name="theme"]')?.addEventListener('change', handleThemeChange)
		return () => {
			document.querySelector('.highlightjs-form vscode-single-select[name="theme"]')?.removeEventListener('change', handleThemeChange)
		}
	}, [handleThemeChange])

	return (
		<>
			<vscode-collapsible title="LLM设置" open>
				<form ref={modelInfoFormRef} onSubmit={(e) => handleSave(modelInfoFormRef, e, 'modelInfo')} onReset={(e) => handleReset(e, 'modelInfo')}>
					<vscode-form-container responsive>
						<vscode-form-group variant="vertical">
							<vscode-label required>模型名称</vscode-label>
							<vscode-single-select value={config.modelInfo?.modelName} name='modelName' required>
								<vscode-option value="deepseek/deepseek-chat">deepseek/deepseek-chat</vscode-option>
								<vscode-option value="deepseek/deepseek-reasoner">deepseek/deepseek-reasoner</vscode-option>
								<vscode-option value="bytedance/doubao-1-5-pro-32k-250115">bytedance/doubao-1-5-pro-32k-250115</vscode-option>
								<vscode-option value="bytedance/doubao-1-5-lite-32k-250115">bytedance/doubao-1-5-lite-32k-250115</vscode-option>
								<vscode-option value="bytedance/deepseek-v3-250324">bytedance/deepseek-v3-250324</vscode-option>
								<vscode-option value="bytedance/deepseek-r1-250120">bytedance/deepseek-r1-250120</vscode-option>
							</vscode-single-select>
							<vscode-form-helper>
						</vscode-form-helper>
						</vscode-form-group>
						<vscode-form-group variant="vertical">
							<vscode-label required>API Key</vscode-label>
							<vscode-textfield required value={config.modelInfo?.apiKey} placeholder='请输入模型的Api Key' name='apiKey'></vscode-textfield>
						</vscode-form-group>
						<vscode-form-group variant="vertical">
							<vscode-label>Base Url</vscode-label>
							<vscode-textfield value={config.modelInfo?.baseUrl} placeholder='请输入模型的Base Url' name='baseUrl'></vscode-textfield>
						</vscode-form-group>
						<vscode-form-group variant="vertical">
							<vscode-label>Max Tokens</vscode-label>
							<vscode-textfield type='number' value={config.modelInfo?.maxTokens} placeholder='请输入模型的Max Tokens' name='maxTokens'></vscode-textfield>
						</vscode-form-group>
						<vscode-form-group variant="vertical">
							<vscode-label>Temperature</vscode-label>
							<vscode-textfield type='number' min={0} step={0.1} value={config.modelInfo?.temperature} placeholder='请输入模型的Temperature' name='temperature'></vscode-textfield>
						</vscode-form-group>
						<vscode-form-group variant="vertical">
							<vscode-label>AK</vscode-label>
							<vscode-textfield value={config.modelInfo?.ak} placeholder='请输入模型的AK' name='ak'></vscode-textfield>
						</vscode-form-group>
						<vscode-form-group variant="vertical">
							<vscode-label>SK</vscode-label>
							<vscode-textfield value={config.modelInfo?.sk} placeholder='请输入模型的SK' name='sk'></vscode-textfield>
						</vscode-form-group>
						<vscode-form-group variant="vertical">
							<vscode-button type='submit'>保存</vscode-button>
							<vscode-button secondary type='reset'>取消</vscode-button>
						</vscode-form-group>
					</vscode-form-container>
				</form>
			</vscode-collapsible>
			<vscode-collapsible title="数据库设置">
				<form ref={databaseFormRef} onSubmit={(e) => handleSave(databaseFormRef, e, 'database')} onReset={(e) => handleReset(e, 'database')}>
					<vscode-form-container>
							<vscode-form-group variant="vertical">
								<vscode-label>数据库类型</vscode-label>
								<vscode-single-select value={config.database?.type} name='type'>
									<vscode-option value="mysql">mysql</vscode-option>
								</vscode-single-select>
							</vscode-form-group>
							<vscode-form-group variant="vertical">
								<vscode-label>数据库权限</vscode-label>
								<vscode-single-select value={config.database?.mode} name='mode'>
									<vscode-option value="admin">管理员</vscode-option>
									<vscode-option value="write">读写</vscode-option>
									<vscode-option value="read">仅读取</vscode-option>
								</vscode-single-select>
							</vscode-form-group>
							<vscode-form-group variant="vertical">
								<vscode-label>链接字符串</vscode-label>
								<vscode-textfield value={config.database?.connectionString} placeholder='请输入数据库地址' name='connectionString'></vscode-textfield>
							</vscode-form-group>
							<vscode-form-group variant="vertical">
								<vscode-button type='submit'>保存</vscode-button>
								<vscode-button secondary type='reset'>取消</vscode-button>
							</vscode-form-group>
					</vscode-form-container>
				</form>
			</vscode-collapsible>
			<vscode-collapsible title="项目模板设置">
				<form ref={projectTemplateFormRef} onSubmit={(e) => handleSave(projectTemplateFormRef, e, 'projectTemplate')} onReset={(e) => handleReset(e, 'projectTemplate')}>
					<vscode-form-container>
						<vscode-form-group variant="vertical">
							<vscode-label>模板类型</vscode-label>
							<vscode-single-select value={config.projectTemplate?.type} name='type'>
								<vscode-option value="admin">网络模板</vscode-option>
								<vscode-option value="write">本地模板</vscode-option>
							</vscode-single-select>
						</vscode-form-group>
						<vscode-form-group variant="vertical">
							<vscode-label>模板地址</vscode-label>
							<vscode-textfield value={config.projectTemplate?.url} placeholder='请输入模板地址' name='url'></vscode-textfield>
						</vscode-form-group>
						<vscode-form-group variant="vertical">
							<vscode-label>模板路径</vscode-label>
							<vscode-textfield type='file' value={config.projectTemplate?.path} placeholder='请输入模板路径' name='path'></vscode-textfield>
						</vscode-form-group>
						<vscode-form-group variant="vertical">
							<vscode-label>模板名称</vscode-label>
							<vscode-textfield value={config.projectTemplate?.name} placeholder='请输入模板名称' name='name'></vscode-textfield>
						</vscode-form-group>
						<vscode-form-group variant="vertical">
							<vscode-button type='submit'>保存</vscode-button>
							<vscode-button secondary type='reset'>取消</vscode-button>
						</vscode-form-group>
					</vscode-form-container>
				</form>
			</vscode-collapsible>
			<vscode-collapsible title="代码高亮设置">
				<form className='highlightjs-form' ref={highlightjsFormRef} onSubmit={(e) => handleSave(highlightjsFormRef, e, 'highlightjs')} onReset={(e) => handleReset(e, 'highlightjs')}>
					<vscode-form-container>
					<vscode-form-group variant="vertical">
							<vscode-label>主题</vscode-label>
							<vscode-single-select value={config.highlightjs?.theme} name='theme'>
								{
									config.highlightjs?.themes?.map((item) => {
										return <vscode-option value={item} key={item}>{item}</vscode-option>	
									})
								}
							</vscode-single-select>
						</vscode-form-group>
						<vscode-form-group variant="vertical">
							<vscode-label>样式</vscode-label>
							<vscode-textarea value={config.highlightjs?.content} placeholder='请输入样式' name='content' rows={30}></vscode-textarea>
						</vscode-form-group>
						<vscode-form-group variant="vertical">
							<vscode-button type='submit'>保存</vscode-button>
							<vscode-button secondary type='reset'>取消</vscode-button>
						</vscode-form-group>
					</vscode-form-container>
				</form>
			</vscode-collapsible>
		</>
	)
})